package billrestauration.daos;
 
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import billrestauration.entities.Role;
import billrestauration.entities.Utilisateur;

public class ExtraDao implements UserDetailsService {
	@Value("${authentication.usernamenotfound")
	private String  usernamenotfound;
	public MainDao getDao() {
		return dao;
	}

	public void setDao(MainDao dao) {
		this.dao = dao;
	}

	private  MainDao dao;
	 
	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		// TODO Auto-generated method stub
		Utilisateur u=dao.loadUserByUsername(username);
		if(null==u)throw new UsernameNotFoundException(usernamenotfound);
		Collection<GrantedAuthority> aut=new  ArrayList<GrantedAuthority>();
		List<Role> l=dao.find("select new Role(r.role,u) from Utilisateur u, Role r where u.username=r.utilisateur.username"
				+ " and u.username=?", username);
		List<Role> l2=dao.find("select new Role(gr.rolegroupe,u) "
				+ " from Utilisateur u , Groupe g,GroupUtilisateur gu,GroupeRole gr "
				+ " where "
				+ " u.username=gu.utilisateur.username "
				+ " and g.nomgroupe=gu.groupe.nomgroupe"
				+ " and gr.groupe.nomgroupe=g.nomgroupe "
				+ " and u.username=? ",username);
		if(null!=l)
		for (Role role : l) {
			aut.add(new GrantedAuthorityImpl(role.getRole()));
		}
		if(null!=l2)
		for (Role role : l2) {
			aut.add(new GrantedAuthorityImpl(role.getRole()));
		}
		UserDetails user=new Utilisateur(username, u.getPassword(), aut);
		System.out.println(user);
		return user;
	}
}
